<?php
namespace src\logic;
use classlib\acl;
use \classlib\core as C;
use classlib\core\view\view_abstract;
class lsignin {
	//密码错误8次锁定5分钟
	const ERRORLOCK = 8;
	const LOCKEXPIRE= 300;
	//每个IP每天最多注册15个账号
	const IPREGISTER= 16;
	
	//设置登录跟踪代码
	public static function track($userid, $loginpw, $cookie=true, $auto=1) {
		$expire  = ($auto == 1)? C\config::$nowtime + 86400*7:0;
		$acl     = acl::inst('ACLweb');
		$loginpw = $acl->ss($userid, $loginpw, $expire);
		$luser   = array('id'=>$userid, 'st'=>substr(C\config::$nowtime, 5));
		return $acl->signin($luser, $loginpw, $expire, $cookie);
	}
	
	/**
	 * 验证是否是合法的密码串
	 * @param string $chk_data
	 * @return boolean
	 */
	public static function is_loginpw($chk_data) {
		return preg_match('/^[^\s]{6,20}$/', $chk_data);
	}
	
	/**
	 * 登录验证条件判断
	 * @param string $account
	 * @param string $loginpw
	 * @param view_abstract $view
	 */
	public static function login($account, $loginpw, $view) {
		$lang = C\lang::inst('web');
		if (!filter_var($account, FILTER_VALIDATE_EMAIL)) {//账号是邮箱的话使用邮箱登录
			$view->assign_error(80001, $lang->txt('action', '80001'));
		}
		$ip   = C\get_ip();
		$ekey = 'err_'.ip2long($ip);
		$num  = (int)C\model::$cacher->get($ekey);
		if ($num > self::ERRORLOCK) {
			$num += 1;
			C\model::$cacher->set($ekey, $num, self::LOCKEXPIRE);
			$view->assign_error(703, $lang->txt('core', '703'));
		}
		$res  = lsocial::login($account, $loginpw);
		//登录验证不通过的时候提示错误
		if ($res['result'] != '000') {
			C\model::$cacher->set($ekey, $num+1, self::LOCKEXPIRE);
			$view->assign_error(80005, $lang->txt('action', '80005'));
		}
		//处理资料信息的同步更新
		$user = self::sync_user($res['value'], $loginpw);
		if ($user['status'] != 1) {
			$view->assign_error(80008, $lang->txt('action', '80008'));
		}
		//记录登录日志信息
		$field = array('userid'=>$user['userid'], 'account'=>$account, 'logip'=>$ip,
			'version'=>'web1.0', 'os'=>$_SERVER['HTTP_USER_AGENT'], 'stime'=>C\config::$nowtime);
		C\model::load('main.log.login')->new_one($field);
		return $user;
	}
	
	/**
	 * 建立连接关系映射，这里也是使用Psocal userId/200w 
	 * @param int $uin
	 * @return int $userid
	 */
	public static function attrps($uin) {
		$orm   = C\model::load('main.pl.attrpsocial')->set_dev($uin);
		$user  = $orm->get_one($uin);
		if (!$user) {
			$user  = array('uin'=>$uin, 'userid'=>C\model::max_id('userinfo'));
			$orm->new_one($user);
			setcookie('isnew', 1, 0, '/');//记录是新用户
		}
		return $user['userid'];
	}
	
	/**
	 * 同步更新用户信息到PShow
	 * @param array $psocial
	 * @param string $loginpw
	 * @return array $userid
	 */
	public static  function sync_user($psocial, $loginpw, $isthird=false, $origin=0) {
		$userid  = self::attrps($psocial['userId']);
		//查看绑定的用户信息是否已经存在，更新或者新增一个用户
		$orm     = C\model::load('main.pl.userinfo')->set_dev($userid);
		$user    = $orm->get_one($userid);
		$loginpw = \classlib\acl::inst('ACLweb')->crypt($loginpw);
		if (!$user) {
			$isthirdset = $isthird? 0:1;
			$nick       = trim($psocial['firstName'].' '.$psocial['lastName']);
			lnickuin::addset($userid, $nick);
			$thumb      = lshare::AVTAR;
			if (isset($psocial['userProfilePictures'][0]['thumbnailPath']) && $psocial['userProfilePictures'][0]['thumbnailPath']) {
				$thumb  = lupfile::dopic($psocial['userProfilePictures'][0]['thumbnailPath'], 'jpg', 'avtar', $user['userid']);
				(!$thumb) && $thumb = lshare::AVTAR;
			}
			$sex   = (!isset($psocial['gender']) || $psocial['gender'] == 'M')? 1:2;
			$user  = array('userid'=>$userid, 'uin'=>$psocial['userId'], 'origin'=>$origin, 'loginpw'=>$loginpw, 'lv'=>1,
				'isthirdset'=>$isthirdset, 'token'=>$psocial['token'], 'nickname'=>$nick, 'thumb'=>$thumb, 'sex'=>$sex,
				'email'=>$psocial['email'], 'lastip'=>C\get_ip(), 'lasttime'=>C\config::$nowtime, 'regtime'=>C\config::$nowtime,
				'status'=>1, 'emailverify'=>intval($psocial['emailVerifyYn']), 'stime'=>C\config::$nowtime);
			$orm->new_one($user);
			//默认插入一条财务信息
			C\model::load('main.pl.finance')->set_dev($userid)->new_one(array('userid'=>$userid));
		} else {
			$field = array('loginpw'=>$loginpw, 'token'=>$psocial['token'], 'email'=>$psocial['email'],
					'emailverify'=>intval($psocial['emailVerifyYn']), 'lastip'=>C\get_ip(), 'lasttime'=>C\config::$nowtime);
			if (isset($psocial['userProfilePictures'][0]['thumbnailPath']) && $user['thumb'] == lshare::AVTAR) {
				$thumb = lupfile::dopic($psocial['userProfilePictures'][0]['thumbnailPath'], 'jpg', 'avtar', $user['userid']);
				($thumb) && $field['thumb'] = $thumb;
			}
			$orm->save($userid, $field);
		}
		return $user;
	}
	
	/**
	 * 会员注册公共接口信息
	 * @param view_abstract $view
	 * @param string $email
	 * @param string $nick
	 * @param string $loginpw
	 */
	public static function register($view, $email, $nick, $loginpw) {
		$ip   = C\get_ip();
		$lang = C\lang::inst('web');
		$ekey = 'reg_'.date('Ymd').'_'.ip2long($ip);
		$num  = (int)C\model::$cacher->get($ekey);
		if ($num > self::IPREGISTER) {
			$view->assign_error(703, $lang->txt('core', '703'));
		}
		//账号是邮箱的话使用邮箱登录
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$view->assign_error(80018, $lang->txt('action', '80018'));
		}
		$nlen = mb_strlen($nick, 'utf-8');
		if ($nlen < 2 || $nlen > 30 || trim($nick) == '') {
			$view->assign_error(80002, $lang->txt('action', '80002'));
		}
		if (lnickuin::exist($nick)) {//验证注册的昵称是否重复
			$view->assign_error(80033, $lang->txt('action', '80033'));
		}
		//验证屏蔽关键词
		$res = limapi::filter(2, $nick);
		if ($res && $res['ResultContent'] == 1) {
			$nickerr = $lang->txt('filter', 'nickname');
			$view->assign_error(80033, $lang->txt('action', '80088', $nickerr));
		}
		//调用PSocial看看注册是否合法
		$res = lsocial::register($email, $loginpw, $nick);
		if ($res['result'] != '000') {
			$view->assign_error(80018, $res['message']);
		}
		//更新同步信息到本地的业务信息
		$user     = self::sync_user($res['value'], $loginpw);
		if ($user['status'] != 1) {
			$view->assign_error(80008, $lang->txt('action', '80008'));
		}
		//记录登录日志信息
		$field = array('userid'=>$user['userid'], 'account'=>$email, 'logip'=>$ip,
				'version'=>'web1.0', 'os'=>$_SERVER['HTTP_USER_AGENT'], 'stime'=>C\config::$nowtime);
		C\model::load('main.log.login')->new_one($field);
		C\model::$cacher->set($ekey, $num+1, 86400);
		return $user;
	}
}